package com.bbbk.util.word;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xwpf.converter.core.IXWPFConverter;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.bbbk.util.word.conf.Result;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

@Controller
public class WordControlle {
	
	@Value("${template.path}")
	private String templatePath;
	
	@Autowired
	private Word2007 word2007;
	

	@Value("${pdf.path}")
	private String pdfpath;

	@RequestMapping("/v2/builderPdf")
	@ResponseBody
	public Result<?> builderPdf(@RequestBody Param param) throws Exception {

		File templateFile = new File(templatePath + param.getTemplatePath());
		if (!templateFile.exists()) {
			throw new RuntimeException("模板文件不存在:" + templatePath + param.getTemplatePath());
		}

		File pdfFile = new File(pdfpath + param.getPdfPath());
		if (pdfFile.exists()) {
			throw new RuntimeException("PDF文件已存在:" + param.getPdfPath());
		} else {
			if (!pdfFile.getParentFile().exists()) {
				boolean mkdirs = pdfFile.getParentFile().mkdirs();
				if (!mkdirs)
					throw new RuntimeException("创建PDF存放路径失败:" + pdfFile.getParentFile().getAbsolutePath());
			}
			boolean createNewFile = pdfFile.createNewFile();
			if (!createNewFile)
				throw new RuntimeException("创建PDF文件失败:" + pdfFile.getAbsolutePath());
		}

		FileOutputStream outputStream = new FileOutputStream(pdfFile);

		Object object = null;
		if (StrUtil.isBlank(param.getJsonDataStr())) {
			object = new HashMap<>();
		} else {
			object = JSON.parseObject(param.getJsonDataStr());
		}

		word2007.builderPdf(new FileInputStream(templateFile), outputStream, object);
		outputStream.flush();
		outputStream.close();
		HashMap<String, Object> result = new HashMap<>();
		result.put("templateFile", templateFile.getAbsolutePath());
		result.put("pdfPath", pdfFile.getAbsolutePath());
		return Result.success(result);
	}

	@RequestMapping("/word2pdf")
	public void word2pdf(HttpServletResponse response,MultipartFile file) throws IOException {
		response.setHeader("Content-Disposition", "attachment;filename="+111+".pdf");
		response.setContentType("application/octet-stream");
		XWPFDocument xwpfDocument = new XWPFDocument(file.getInputStream());
		PdfOptions pdfOptions = PdfOptions.create();
		IXWPFConverter<PdfOptions> Instance = PdfConverter.getInstance();
		Instance.convert(xwpfDocument, response.getOutputStream(), pdfOptions);
		response.setHeader("Content-Disposition", "attachment;filename="+111+".pdf");
	}
	@RequestMapping("/")
	public void index(HttpServletResponse response) throws IOException {
		response.sendRedirect("1.html");
	}
	
	@RequestMapping("builderWord")
	@ResponseBody
	public void builderWord(HttpServletResponse response,String id,String jsonDataStr) throws Exception{
		response.setHeader("Content-Disposition", "attachment;filename="+id+".doc");
		response.setContentType("application/octet-stream");
		ServletOutputStream outputStream = response.getOutputStream();
		Object object = null;
		if(StrUtil.isBlank(jsonDataStr)) {
			object = new HashMap<>();
		}else {
			object = JSON.parseObject(jsonDataStr);
		}
		word2007.builderWord(getTemplateStream(id), outputStream, object);
	}


	@RequestMapping("builderPdf")
	public void builderPdf(HttpServletResponse response,String id,String jsonDataStr) throws Exception{
		
		response.setContentType("application/pdf");
		response.setHeader("Content-Disposition", "attachment;filename="+id+".pdf");
		
		ServletOutputStream outputStream = response.getOutputStream();
		
		Object object = null;
		if(StrUtil.isBlank(jsonDataStr)) {
			object = new HashMap<>();
		}else {
			object = JSON.parseObject(jsonDataStr);
		}
		
		word2007.builderPdf(getTemplateStream(id), outputStream, object);
		outputStream.flush();

	}
	/**
	 * 模板下载
	 * @param id
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * @throws IORuntimeException 
	 */
	@RequestMapping("downloadTemplate")
	public void downloadTemplate(String id,HttpServletResponse response) throws Exception{
		File file = getTemplateFile(id);
		if(file!=null) {
			response.getOutputStream().write(IoUtil.readBytes(new FileInputStream(file)));
			response.getOutputStream().flush();
		}else {
			throw new RuntimeException("模板不存在");
		}
	}
	/**
	 * 模板是否存在
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("templateIsExists")
	@ResponseBody
	public Object templateIsExists( String id) throws Exception{
		File file = getTemplateFile(id);
		if(file!=null) {
			return Result.success(true);
		}else {
			return Result.success(false);
		}
	}
	
	@RequestMapping("uploadTemplate")
	@ResponseBody
	public Object uploadTemplate(MultipartFile file) throws IOException{
		if(file.isEmpty()) {
			new RuntimeException("文件数据为空");
		}
		
		String randomUUID = IdUtil.simpleUUID();
		String originalFilename = file.getOriginalFilename();
		File file1 = new File(templatePath+randomUUID+"____"+originalFilename);
		String absolutePath = file1.getAbsolutePath();
		file1.createNewFile();
		byte[] bytes = file.getBytes();
		IoUtil.write(new FileOutputStream(absolutePath), true, bytes);
		
		return Result.success(randomUUID.toString());
	}
	FileInputStream getTemplateStream(String id) throws IOException {
		File templateFile = getTemplateFile(id);
		if(templateFile==null) {
			throw new RuntimeException("模板文件未找到");
		}else {
			return new FileInputStream(templateFile);
		}
	}
	File getTemplateFile(String id){
		File file = new File(templatePath);
		File[] list = file.listFiles();
		if(list!=null) {
			for (File fileitem : list) {
				String fileName = fileitem.getName();
				if(fileName.startsWith(id)) {
					return fileitem.getAbsoluteFile();
				}
			}
			return null;
		}else {
			return null;
		}
	}

}
